package com.chen.controller;

import com.alibaba.fastjson.JSON;
import com.chen.pojo.Vip;
import com.chen.service.vip.VipService;
import com.chen.util.SystemConstrant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/vip")
public class VipFrontController {

    @Resource
    private VipService vipService;

    /**
     * 注册
     * @param vip
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register",produces = {"application/json;charset=UTF-8"})
    public String register(Vip vip){
        //创建Map集合，保存结果信息
        Map<String,Object> map = new HashMap<String,Object>();
        //调用注册的方法
        if(vipService.addVip(vip)>0){
            map.put(SystemConstrant.SUCCESS,true);
            map.put(SystemConstrant.MESSAGE,"恭喜你,注册成功!");
        }else{
            map.put(SystemConstrant.SUCCESS,false);
            map.put(SystemConstrant.MESSAGE,"很遗憾,注册失败,请重新尝试!");
        }
        return JSON.toJSONString(map);
    }

    /**
     * 检查注册是否重复
     * @param vipNo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkName",produces = {"application/json;charset=UTF-8"})
    public String checkName(String vipNo){
        //创建Map集合，保存结果信息
        Map<String,Object> map = new HashMap<String,Object>();
        //调用注册的方法
        if(vipService.findVipByNo(vipNo) != null){
            map.put(SystemConstrant.EXIST,true);
            map.put(SystemConstrant.MESSAGE,"用户名已被使用，请重新输入!");
        }else{
            map.put(SystemConstrant.EXIST,false);
        }
        return JSON.toJSONString(map);
    }

    /**
     * 登录前台
     * @param vipNo
     * @param vipPassword
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login",produces = {"application/json;charset=UTF-8"})
    public String loginFront(String vipNo, String vipPassword, HttpSession session){

        Map<String,Object> map = new HashMap<String, Object>();
        Vip loginFront = vipService.loginFront(vipNo, vipPassword);
        //判断对象是否为空，不为空表示登录成功
        if (loginFront != null){
            //保存当前登录用户
            session.setAttribute(SystemConstrant.FRONT_LOGINUSER,loginFront);
            map.put(SystemConstrant.SUCCESS,true);//成功
        }else{
            map.put(SystemConstrant.SUCCESS,false);//失败
            map.put(SystemConstrant.MESSAGE,"账号密码错误，登录失败");
        }
        return JSON.toJSONString(map);
    }
}
